//
//  GenerationViewController.m
//  TextToImg
//
//  Created by Garenge on 2019/M/29.
//  Copyright © 2019 鹏鹏. All rights reserved.
//

#import "GenerationViewController.h"
#import <Masonry/Masonry.h>
#import "DisplayView.h"
#import "StepperView.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "SettingViewController.h"
#import "AppTool.h"

#define IsBlockExecute(block, ...) if (block) { block(__VA_ARGS__); };

@interface GenerationViewController () <UITextViewDelegate>

@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) DisplayView *displayView;

@property (nonatomic, assign) CGFloat fontSize; // 15
@property (nonatomic, assign) CGFloat lineSpacing; // 5
@property (nonatomic, assign) CGFloat paragraphSpacing; // 0
@property (nonatomic, assign) CGFloat topMargin;
@property (nonatomic, assign) CGFloat sideMargin;
@property (nonatomic, strong) NSMutableDictionary *mDic;

@property (nonatomic, strong) UIView *operationBackView;
@property (nonatomic, strong) StepperView *fontSV;
@property (nonatomic, strong) StepperView *lineSpacingSV;
@property (nonatomic, strong) StepperView *paraSpacingSV;
@property (nonatomic, strong) StepperView *topMarginSV;
@property (nonatomic, strong) StepperView *sideMarginSV;

@end

@implementation GenerationViewController

static CGFloat defaultFontSize = 15.0;
static CGFloat defaultLineSpacing = 5.0;
static CGFloat defaultParagraphSpacing = 0.0;
static CGFloat defaultTopMargin = 40.0;
static CGFloat defaultSideMargin = 20.0;
static NSString *KEY_FONTSIZE = @"KEY_FONTSIZE";
static NSString *KEY_LINESPACING = @"KEY_LINESPACING";
static NSString *KEY_PARAGRAPHSPACING = @"KEY_PARAGRAPHSPACING";
static NSString *KEY_TOPMARGIN = @"KEY_TOPMARGIN";
static NSString *KEY_SIDEMARGIN = @"KEY_SIDEMARGIN";
#pragma mark 懒加载 setter, getter

#pragma mark 数据持久化
- (void)loadStaticData {
    // 从本地读取设置数据
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    id fontSizeValue = [userDefaults valueForKey:KEY_FONTSIZE];
    if (nil == fontSizeValue) {
        self.fontSize = defaultFontSize;
    } else {
        self.fontSize = [fontSizeValue floatValue];
    }
    
    id lineSpacingValue = [userDefaults valueForKey:KEY_LINESPACING];
    if (nil == lineSpacingValue) {
        self.lineSpacing = defaultLineSpacing;
    } else {
        self.lineSpacing = [lineSpacingValue floatValue];
    }
    
    id paragraphSpacingValue = [userDefaults valueForKey:KEY_PARAGRAPHSPACING];
    if (nil == paragraphSpacingValue) {
        self.paragraphSpacing = defaultParagraphSpacing;
    } else {
        self.paragraphSpacing = [paragraphSpacingValue floatValue];
    }
    
    id topMarginValue = [userDefaults valueForKey:KEY_TOPMARGIN];
    if (nil == topMarginValue) {
        self.topMargin = defaultTopMargin;
    } else {
        self.topMargin = [topMarginValue floatValue];
    }
    
    id sideMarginValue = [userDefaults valueForKey:KEY_SIDEMARGIN];
    if (nil == sideMarginValue) {
        self.sideMargin = defaultSideMargin;
    } else {
        self.sideMargin = [sideMarginValue floatValue];
    }
    
    [self saveStaticData];
}
- (void)saveStaticData {
    // 存储设置数据到本地
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setValue:@(self.fontSize) forKey:KEY_FONTSIZE];
    [userDefaults setValue:@(self.lineSpacing) forKey:KEY_LINESPACING];
    [userDefaults setValue:@(self.paragraphSpacing) forKey:KEY_PARAGRAPHSPACING];
    [userDefaults setValue:@(self.topMargin) forKey:KEY_TOPMARGIN];
    [userDefaults setValue:@(self.sideMargin) forKey:KEY_SIDEMARGIN];
    [userDefaults synchronize];
}


#pragma mark fontSize

- (void)setFontSize:(CGFloat)fontSize {
    _fontSize = fontSize;
    [self.mDic setObject:APPUsualFontWithSize(self.fontSize) forKey:NSFontAttributeName];

    NSMutableParagraphStyle *paragraphStyle = [self.mDic valueForKey:NSParagraphStyleAttributeName];
    [paragraphStyle setFirstLineHeadIndent:2 * fontSize];
}

- (void)resetFontSize {
    self.fontSize = defaultFontSize;
    self.fontSV.value = self.fontSize;
}

#pragma mark lineSpacing

- (void)setLineSpacing:(CGFloat)lineSpacing {
    _lineSpacing = lineSpacing;
    NSMutableParagraphStyle *paragraphStyle = [self.mDic valueForKey:NSParagraphStyleAttributeName];
    [paragraphStyle setLineSpacing:_lineSpacing];
}

- (void)resetLineSpacing {
    self.lineSpacing = defaultLineSpacing;
    self.lineSpacingSV.value = self.lineSpacing;
}

#pragma mark paragraphSpacing

- (void)setParagraphSpacing:(CGFloat)paragraphSpacing {
    _paragraphSpacing = paragraphSpacing;
    NSMutableParagraphStyle *paragraphStyle = [self.mDic valueForKey:NSParagraphStyleAttributeName];
    [paragraphStyle setParagraphSpacing:_paragraphSpacing];
}

- (void)resetParagraphSpacing {
    self.paragraphSpacing = defaultParagraphSpacing;
    self.paraSpacingSV.value = self.paragraphSpacing;
}

#pragma mark topMargin

- (void)resetTopMargin {
    self.topMargin = defaultTopMargin;
    self.topMarginSV.value = self.topMargin;
}

#pragma mark sideMargin

- (void)resetSideMargin {
    self.sideMargin = defaultSideMargin;
    self.sideMarginSV.value = self.sideMargin;
}

- (NSMutableDictionary *)mDic {
    if (nil == _mDic) {
        // set the font type and size
        _mDic = [NSMutableDictionary dictionary];
        
        // 颜色
        //        [mDic setObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
        // 字体STKaiti
        [_mDic setObject:APPUsualFontWithSize(self.fontSize) forKey:NSFontAttributeName];
        // 段间距
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:self.lineSpacing];
        [paragraphStyle setParagraphSpacing:self.paragraphSpacing];
        [_mDic setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
    }
    return _mDic;
}

#pragma mark 界面
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpSubviews];
    [self loadStaticData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self showTitleLabelText];
}

- (void)showTitleLabelText {
    NSString *tipsTitle = @"特殊符号";
    if ([[AppTool sharedAppTool] getSpliteMode] == SplitModeWithString) {
        tipsTitle = [[AppTool sharedAppTool] getSplitString];
        self.titleLabel.text = [NSString stringWithFormat:@"效果图-%ld字-按字符\"%@\"分割", (long)self.textView.text.length, tipsTitle];
    } else if([[AppTool sharedAppTool] getSpliteMode] == SplitModeWithCount) {
        tipsTitle = [NSString stringWithFormat:@"%ld", (long)[[AppTool sharedAppTool] getSpliteTextCount]];
        self.titleLabel.text = [NSString stringWithFormat:@"效果图-%ld字-按字数\"%@\"分割", (long)self.textView.text.length, tipsTitle];
    }
}

- (void)setUpSubviews {
    self.title = @"长截图";
    
    UIBarButtonItem *photoItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"photo"] style:UIBarButtonItemStyleDone target:self action:@selector(jumpToPhotos:)];
    self.navigationItem.leftBarButtonItems = @[photoItem];
    
    UIBarButtonItem *settingItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"setting"] style:UIBarButtonItemStyleDone target:self action:@selector(jumpToSetting:)];
    self.navigationItem.rightBarButtonItems = @[settingItem];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 顶部的文字
    UITextView *textView = [[UITextView alloc] init];
    textView.font = APPUsualFontWithSize(15);
    textView.delegate = self;
    [self.view addSubview:textView];
    self.textView = textView;
    
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(8);
        make.left.equalTo(self.view).with.offset(8);
        make.right.equalTo(self.view).with.offset(-8);
        make.height.mas_equalTo(200);
    }];
    
    textView.layer.borderWidth = 0.5;
    textView.layer.cornerRadius = 5;
    textView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
    // 粘贴
    CGSize buttonSize = CGSizeMake(80, 30);
    UIButton *pasteButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [pasteButton setTitle:@"粘贴" forState:UIControlStateNormal];
    [pasteButton addTarget:self action:@selector(pasteMyContent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pasteButton];
    
    [pasteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textView.mas_bottom).with.offset(8);
        make.left.equalTo(textView).with.offset(8);
        make.size.mas_equalTo(buttonSize);
    }];
    
    pasteButton.layer.cornerRadius = 6;
    pasteButton.layer.borderWidth = 0.5;
    pasteButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    pasteButton.layer.masksToBounds = YES;
    
    // 清空文本
    UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [clearButton setTitle:@"清空" forState:UIControlStateNormal];
    [clearButton addTarget:self action:@selector(clearMyInput:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:clearButton];
    
    [clearButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(pasteButton);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(buttonSize);
    }];
    
    clearButton.layer.cornerRadius = 6;
    clearButton.layer.borderWidth = 0.5;
    clearButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    clearButton.layer.masksToBounds = YES;
    
    // 生成
    UIButton *generateButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [generateButton setTitle:@"预览" forState:UIControlStateNormal];
    [generateButton addTarget:self action:@selector(previewMyPic:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:generateButton];
    
    [generateButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(pasteButton);
        make.right.equalTo(textView).with.offset(-8);
        make.size.mas_equalTo(buttonSize);
    }];
    
    generateButton.layer.cornerRadius = 6;
    generateButton.layer.borderWidth = 0.5;
    generateButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    generateButton.layer.masksToBounds = YES;
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:titleLabel];
    self.titleLabel = titleLabel;
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(generateButton.mas_bottom).with.offset(8);
        make.left.equalTo(textView).with.offset(8);
        make.right.equalTo(textView).with.offset(-8);
        make.height.mas_equalTo(21);
    }];
    
    // 预览
    DisplayView *displayView = [[DisplayView alloc] init];
    displayView.backgroundColor = [UIColor colorWithRed:254.0 / 255.0 green:254.0 / 255.0 blue:254.0 / 255.0 alpha:1];
    [self.view addSubview:displayView];
    self.displayView = displayView;
    
    [displayView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).with.offset(8);
        make.left.equalTo(self.view).with.offset(8);
        make.right.equalTo(self.view).with.offset(-8);
        make.bottomMargin.equalTo(self.view).with.offset(-8);
    }];
    
    displayView.layer.borderWidth = 0.5;
    displayView.layer.cornerRadius = 5;
    displayView.layer.borderColor = [UIColor lightGrayColor].CGColor;
}

#pragma mark 打开相册
- (void)jumpToPhotos:(UIBarButtonItem *)sender {
    //跳转
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"photos-redirect://"]options:@{} completionHandler:^(BOOL success) {}];
}

#pragma mark 设置
- (void)jumpToSetting:(UIBarButtonItem *)sender {
    SettingViewController *settingVC = [[SettingViewController alloc] init];
    [self.navigationController pushViewController:settingVC animated:YES];
}

#pragma mark 粘贴
- (void)pasteMyContent:(UIButton *)sender {
    NSString *content = [[UIPasteboard generalPasteboard] string];
//    NSString *content = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"test.text" ofType:nil] encoding:NSUTF8StringEncoding error:nil];
    if (content.length >= 0) {
        self.textView.text = content;
    }
    [self showTitleLabelText];
}

#pragma mark 清除
- (void)clearMyInput:(UIButton *)sender {
    self.textView.text = @"";
    [self.displayView reloadDisplayWithContent:@"" attribute:self.mDic topMargin:self.topMargin sideMargin:self.sideMargin];
    [self showTitleLabelText];
}

#pragma mark 预览
- (void)previewMyPic:(UIButton *)sender {
    
    [self.view endEditing:YES];
    
    [self refreshDisplayView];
    
    [self showOperationBackView];
}

#pragma mark 弹出操作界面
- (void)showOperationBackView {
    // 从上到下弹出一个view, 操作用
    CGRect windowBounds = self.view.window.bounds;
    UIView *operationBackView = [[UIView alloc] initWithFrame:CGRectMake(0, -windowBounds.size.height, windowBounds.size.width, windowBounds.size.height)];
    operationBackView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    [[UIApplication sharedApplication].keyWindow addSubview:operationBackView];
    self.operationBackView = operationBackView;
    
    [UIView animateWithDuration:0.4 animations:^{
        CGRect newFrame = CGRectMake(0, 0, windowBounds.size.width, windowBounds.size.height);
        operationBackView.frame = newFrame;
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOperationBackView:)];
    // 处理手势冲突
    tap.delegate = (id<UIGestureRecognizerDelegate>)self;
    [operationBackView addGestureRecognizer:tap];
    
    UIView *operationView = [[UIView alloc] initWithFrame:CGRectMake(0, self.naviBarBottomMargin, windowBounds.size.width, OPerationViewHeight)];
    operationView.backgroundColor = [UIColor whiteColor];
    [operationBackView addSubview:operationView];
    
    UILabel *tipsLabel = [[UILabel alloc] init];
    tipsLabel.font = [UIFont systemFontOfSize:15];
    tipsLabel.text = @"首选项:";
    [operationView addSubview:tipsLabel];
    
    [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(operationView).with.offset(5);
        make.left.equalTo(operationView).with.offset(20);
        make.size.mas_equalTo(CGSizeMake(100, 30));
    }];

    UIButton *resetButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [resetButton setTitle:@"重 置" forState:UIControlStateNormal];
    [resetButton addTarget:self action:@selector(resetOperationSettings:) forControlEvents:UIControlEventTouchUpInside];
    [operationView addSubview:resetButton];

    [resetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(operationView).with.offset(-40);
        make.centerY.equalTo(tipsLabel);
        make.size.mas_equalTo(CGSizeMake(104, 30));
    }];
    
    resetButton.layer.cornerRadius = 4;
    resetButton.layer.borderWidth = 1;
    resetButton.layer.borderColor = UIColor.lightGrayColor.CGColor;
    
    // 添加详细项
    // 字体放到设置里面去修改, 涉及到下载和加载过程
    // . 字号
    StepperView *fontSV = [self createOperationItemOnSuperView:operationView BasedOn:tipsLabel WithTitle:@"字号(10~25)" defaultValue:self.fontSize maxValue:25 minValue:10 operationBlock:^(NSInteger value) {
        self.fontSize = (CGFloat)value;
        [self refreshDisplayView];
    }];
    self.fontSV = fontSV;
    // . 行间距
    StepperView *lineSpacingSV = [self createOperationItemOnSuperView:operationView BasedOn:fontSV WithTitle:@"行间距(1~10)" defaultValue:self.lineSpacing maxValue:10 minValue:1 operationBlock:^(NSInteger value) {
        self.lineSpacing = (CGFloat)value;
        [self refreshDisplayView];
    }];
    self.lineSpacingSV = lineSpacingSV;
    // . 段间距
    StepperView *paraSpacingSV = [self createOperationItemOnSuperView:operationView BasedOn:lineSpacingSV WithTitle:@"段间距(0~25)" defaultValue:self.paragraphSpacing maxValue:25 minValue:0 operationBlock:^(NSInteger value) {
        self.paragraphSpacing = (CGFloat)value;
        [self refreshDisplayView];
    }];
    self.paraSpacingSV = paraSpacingSV;
    // . 顶部间距
    StepperView *topMarginSV = [self createOperationItemOnSuperView:operationView BasedOn:paraSpacingSV WithTitle:@"顶部间距(20~60)" defaultValue:self.topMargin maxValue:60 minValue:20 operationBlock:^(NSInteger value) {
        self.topMargin = (CGFloat)value;
        [self refreshDisplayView];
    }];
    self.topMarginSV = topMarginSV;
    // . 两边间距
    StepperView *sideMarginSV = [self createOperationItemOnSuperView:operationView BasedOn:topMarginSV WithTitle:@"两边间距(10~50)" defaultValue:self.sideMargin maxValue:50 minValue:10 operationBlock:^(NSInteger value) {
        self.sideMargin = (CGFloat)value;
        [self refreshDisplayView];
    }];
    self.sideMarginSV = sideMarginSV;
    
    // 字体
    UILabel *fontLabel = [[UILabel alloc] init];
    fontLabel.text = @"字体";
    fontLabel.font = [UIFont systemFontOfSize:15];
    [operationView addSubview:fontLabel];
    
    [fontLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(sideMarginSV.mas_bottom).with.offset(6.5);
        make.left.mas_equalTo(20);
        make.height.mas_equalTo(21);
        make.width.mas_equalTo(50);
    }];
    
    UIButton *fontButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [fontButton setTitle:@"华文楷体" forState:UIControlStateNormal];
    [fontButton.titleLabel setFont:APPUsualFontWithSize(15)];
    [operationView addSubview:fontButton];
    
    [fontButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(fontLabel);
        make.right.mas_equalTo(operationView).multipliedBy(0.5).with.offset(-20);
        make.size.mas_equalTo(CGSizeMake(90, 30));
    }];
    
    fontButton.layer.cornerRadius = 4;
    fontButton.layer.borderColor = UIColor.lightGrayColor.CGColor;
    fontButton.layer.borderWidth = 1;
    
    UIView *midLine = [[UIView alloc] init];
    midLine.backgroundColor = [UIColor colorWithRed:8.0 / 255.0 green:158.0 / 255.0 blue:254.0 / 255.0 alpha:1];
    [operationView addSubview:midLine];
    
    [midLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(1, 40));
        make.centerY.equalTo(fontLabel);
        make.centerX.equalTo(operationView);
    }];
    
    // 颜色
    UILabel *colorLabel = [[UILabel alloc] init];
    colorLabel.text = @"颜色";
    colorLabel.font = [UIFont systemFontOfSize:15];
    [operationView addSubview:colorLabel];
    
    [colorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(sideMarginSV.mas_bottom).with.offset(6.5);
        make.left.equalTo(operationView.mas_right).multipliedBy(0.5).with.offset(20);
        make.height.mas_equalTo(21);
        make.width.mas_equalTo(50);
    }];
    
    UIButton *colorButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [colorButton setBackgroundColor:[UIColor whiteColor]];
    [colorButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [operationView addSubview:colorButton];
    
    [colorButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(colorLabel);
        make.right.mas_equalTo(operationView).with.offset(-20);
        make.size.mas_equalTo(CGSizeMake(40, 30));
    }];
    
    colorButton.layer.cornerRadius = 4;
    colorButton.layer.borderColor = UIColor.lightGrayColor.CGColor;
    colorButton.layer.borderWidth = 1;
    
    // 确定按钮
    UIButton *completeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [completeButton.titleLabel setFont:[UIFont systemFontOfSize:18]];
    [completeButton setTitle:@"生成图片" forState:UIControlStateNormal];
    [completeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [completeButton setBackgroundColor:[UIColor colorWithRed:8.0 / 255.0 green:158.0 / 255.0 blue:254.0 / 255.0 alpha:1]];
     // [UIColor colorWithRed:8.0 / 255.0 green:158.0 / 255.0 blue:254.0 / 255.0 alpha:0.5]];
    [completeButton addTarget:self action:@selector(generateMyPic:) forControlEvents:UIControlEventTouchUpInside];
//    completeButton.alpha = 0.5;
    [operationBackView addSubview:completeButton];
    
    [completeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(operationView).with.offset(20);
        make.right.equalTo(operationView).with.offset(-20);
        make.height.mas_equalTo(70);
        make.bottom.mas_equalTo(-70);
    }];
    
    completeButton.layer.cornerRadius = 6;
    completeButton.layer.borderWidth = 0.5;
    completeButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
}

#pragma mark 重置操作选项
- (void)resetOperationSettings:(id)sender {
    [self resetFontSize];
    [self resetLineSpacing];
    [self resetParagraphSpacing];
    [self resetTopMargin];
    [self resetSideMargin];
    [self refreshDisplayView];
    [self saveStaticData];
}

#pragma mark 生成图片
- (void)generateMyPic:(UIButton *)sender {
    [self hideOperationBackView];
    [SVProgressHUD showWithStatus:@"正在制作..."];
    SplitMode splitMode = [[AppTool sharedAppTool] getSpliteMode];
    if (splitMode == SplitModeWithCount) {
        [self generateMyPicWithTextCount];
    } else if (splitMode == SplitModeWithString) {
        [self generateMyPicWithString];
    }
    
    [self saveStaticData];
}

#pragma mark 按照字数分页
- (void)generateMyPicWithTextCount {
    NSInteger splitCount = [[AppTool sharedAppTool] getSpliteTextCount];
    if (splitCount > 0) {
        if (self.textView.text.length > splitCount) {
            [SVProgressHUD dismiss];

            NSMutableArray *contentsMArray = [NSMutableArray array];
            NSString *contentString = self.textView.text;

            NSInteger index = 0;
            NSInteger length = 1;
            NSRange range = NSMakeRange(index, length);

            BOOL customSplite = [[AppTool sharedAppTool] getCustomSplite];

//            CFAbsoluteTime refTime = CFAbsoluteTimeGetCurrent();

            while (index < contentString.length) {

                if (customSplite) {
                    /** 智能分页
                     *  1. 往后数字数, 如果分页后剩余页面不超过25%, 合并作一页
                     *  2. 往前往后数回车 \n, 截取到最近的回车(优先往后, 如果往后比往前大50%的话, 取前面的回车)
                     *  // 3. 截取大段落 \n\n (待分析)
                     *  4. 想到再说吧
                     */
                    // TODO
                    // 严格按照字数分页
                    length = (contentString.length - index) > splitCount ? splitCount : (contentString.length - index);
                } else {
                    // 严格按照字数分页
                    length = (contentString.length - index) > splitCount ? splitCount : (contentString.length - index);
                }

                range = NSMakeRange(index, length);
                NSString *spString = [contentString substringWithRange:range];
                [contentsMArray addObject:spString];
                index += length;
            }
//            NSLog(@"循环结束: after busy %f", CFAbsoluteTimeGetCurrent() - refTime);

            if (contentsMArray.count > 1) {
                [self AlertTarget:self title:@"提示" message:[NSString stringWithFormat:@"将分割成%lu页, 是否继续?", (unsigned long)contentsMArray.count] sureTitle:@"确定" sureAction:^{
                    for (NSString *string in contentsMArray) {
                        [self createMyPicAndSaveToAlbumWithString:string complete:NO];
                    }
                    [self generateCompleteHandler];
                } cancleTitle:@"取消" cancleAction:^{

                }];
            } else {
                [self createMyPicAndSaveToAlbumWithString:self.textView.text complete:YES];
            }
        } else {
            [self createMyPicAndSaveToAlbumWithString:self.textView.text complete:YES];
        }
    } else {
        // 0 不分页
        [self createMyPicAndSaveToAlbumWithString:self.textView.text complete:YES];
    }
}

#pragma mark 按照特殊字符分页
- (void)generateMyPicWithString {
    NSString *splitString = [[AppTool sharedAppTool] getSplitString];
    if (splitString.length > 0) {
        NSArray *contentsArray = [self.textView.text componentsSeparatedByString:splitString];
        if (contentsArray.count > 1) {
            [SVProgressHUD dismiss];
            [self AlertTarget:self title:@"提示" message:[NSString stringWithFormat:@"将分割成%ld页, 是否继续?", (long)contentsArray.count] sureTitle:@"确定" sureAction:^{
                for (NSString *string in contentsArray) {
                    [self createMyPicAndSaveToAlbumWithString:[NSString stringWithFormat:@"%@", string] complete:NO];
                }
                [self generateCompleteHandler];
            } cancleTitle:@"取消" cancleAction:^{

            }];
        } else {
            [self createMyPicAndSaveToAlbumWithString:self.textView.text complete:YES];
        }
    } else {
        [self createMyPicAndSaveToAlbumWithString:self.textView.text complete:YES];
    }
}

#pragma mark 保存图片到本地相册
- (void)createMyPicAndSaveToAlbumWithString:(NSString *)string complete:(BOOL)complete {

    __weak typeof(self) weakSelf = self;
    [self imageFromText:string completeHandler:^(UIImage *image, NSInteger errorCode) {

        [SVProgressHUD dismiss];

        switch (errorCode) {
            case 1: {
                // 图片过长或者过宽, 直接生成png图像, 打开分享
                NSData *data = UIImagePNGRepresentation(image);
                NSURL *fileURL = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", [self getRandomTimeString]]]];
                [data writeToURL:fileURL atomically:YES];
                [weakSelf shareWithActivityItems:@[fileURL] sourceView:self.view completionWithItemsHandler:^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {

                    if (!completed) {
                        return;
                    }

                    if (complete) {
                        [weakSelf generateCompleteHandler];
                    }
                }];
            }
                break;
            case -1: {
                UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
                if (complete) {
                    [self generateCompleteHandler];
                }
            }
                break;
            default:
                NSLog(@"createMyPicAndSaveToAlbumWithString 未知错误");
                break;
        }
    }];
}

- (NSString *)getRandomTimeString {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = [NSString stringWithFormat:@"yyyyMMddHHmmssSSS%04ld", arc4random() % 10000];
    return [formatter stringFromDate:[NSDate date]];//202210211533314208168
}

- (void)generateCompleteHandler {
    [SVProgressHUD dismiss];
    [SVProgressHUD showSuccessWithStatus:@"制作结束"];
}

- (void)refreshDisplayView {
    [self.displayView reloadDisplayWithContent:self.textView.text attribute:self.mDic topMargin:self.topMargin sideMargin:self.sideMargin];
}

- (StepperView *)createOperationItemOnSuperView:(UIView *)superView BasedOn:(UIView *)baseView WithTitle:(NSString *)title defaultValue:(NSInteger)value maxValue:(NSInteger)maxValue minValue:(NSInteger)minValue operationBlock:(StepperViewBlock)complete {
    StepperView *stepperView = [[StepperView alloc] init];
    stepperView.maxValue = maxValue;
    stepperView.minValue = minValue;
    stepperView.title = title;
    stepperView.value = value;
    stepperView.operationBlock = complete;
    [superView addSubview:stepperView];
    
    [stepperView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(baseView.mas_bottom).with.offset(1);
        make.left.equalTo(superView).with.offset(20);
        make.right.equalTo(superView).with.with.offset(-20);
        make.height.mas_equalTo(32);
    }];
    
    return stepperView;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark 点击操作界面
- (void)tapOperationBackView:(UITapGestureRecognizer *)sender {
    // 点击空白处消失
    [self hideOperationBackView];
}

// 隐藏操作界面
- (void)hideOperationBackView {
    if (self.operationBackView) {
        self.operationBackView.hidden = YES;
        [self.operationBackView removeFromSuperview];
        self.operationBackView = nil;
    }
}

// 处理手势冲突
static CGFloat OPerationViewHeight = 250.0f;
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
       shouldReceiveTouch:
(UITouch *)touch {
    // 输出点击的view的类名
    CGPoint point = [touch locationInView:self.operationBackView]; //返回触摸点在视图中的当前坐标
    int y = point.y;
    if (y <= self.naviBarBottomMargin || y >= self.naviBarBottomMargin + OPerationViewHeight + 20) {
        return YES;
    } else {
        return NO;
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *msg = nil ;
    if(nil == error){
        msg = @"保存图片成功" ;
    }else{
        msg = [NSString stringWithFormat:@"保存图片失败, error: %@", error] ;
    }
    NSLog(@"ContextInfo: %@", contextInfo);
    NSLog(@"msg: %@", msg);
}

#pragma mark UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    [self showTitleLabelText];
}

#pragma mark 生成图片
- (CGFloat)CONTENT_MAX_WIDTH {
    return self.displayView.bounds.size.width - 2 * self.sideMargin;
}

/// 根据文字生成图片
/// - Parameters:
///   - content: 文字
///   - completeHandler: 回调, errorCode默认-1表示成功, 1表示图片过长或者过宽
- (void)imageFromText:(NSString *)content completeHandler:(void(^)(UIImage *image, NSInteger errorCode))completeHandler {
    
    CGFloat fHeight = 0.0f;
    CGRect stringRect = [content boundingRectWithSize:CGSizeMake([self CONTENT_MAX_WIDTH], CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:self.mDic context:nil];
    fHeight += stringRect.size.height + self.topMargin;

    NSInteger errorCode = -1;
    if (stringRect.size.width >= 20000 || stringRect.size.height >= 20000) {
        // 错误1: 图片过长或者过宽 (简略测试, 21000以上长度的图片就会失败)
        NSLog(@"imageFromText 图片尺寸: %@", NSStringFromCGSize(stringRect.size));
        errorCode = 1;
    }

    CGSize newSize = CGSizeMake([self CONTENT_MAX_WIDTH] + 2 * self.sideMargin,  fHeight + self.topMargin);
    
    UIGraphicsBeginImageContextWithOptions(newSize,NO,0.0);
    CGRect rect = CGRectMake(self.sideMargin, self.topMargin, [self CONTENT_MAX_WIDTH], fHeight);
    [content drawInRect:rect withAttributes:self.mDic];
    // transfer image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    IsBlockExecute(completeHandler, image, errorCode);
}

/// 调用系统分享
- (void)shareWithActivityItems:(NSArray *)ctivityItems sourceView:(UIView *)sourceView completionWithItemsHandler:(nonnull UIActivityViewControllerCompletionWithItemsHandler)completionWithItemsHandler {

    UIViewController *topRootViewController = self;
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:ctivityItems applicationActivities:nil];
    activityVC.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray *__nullable returnedItems, NSError *__nullable activityError) {
        NSLog(@"调用分享的应用id :%@", activityType);
        if (completed) {
            NSLog(@"分享成功!");
        } else {
            NSLog(@"分享失败!, error: %@", activityError);
        }
        IsBlockExecute(completionWithItemsHandler, activityType, completed, returnedItems, activityError);
    };

    if ([[UIDevice currentDevice].model isEqualToString:@"iPhone"]) {
        [topRootViewController presentViewController:activityVC animated:YES completion:nil];
    } else if ([[UIDevice currentDevice].model isEqualToString:@"iPad"]) {
        UIPopoverPresentationController *popover = activityVC.popoverPresentationController;
        if (popover) {
            popover.sourceView = sourceView;
            popover.permittedArrowDirections = UIPopoverArrowDirectionUp;
        }
        [topRootViewController presentViewController:activityVC animated:YES completion:nil];
    } else {
        //do nothing
    }
}
@end
